﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Tezzanator.Net.XNAGUI.Controls
{
    public class PictureButton : BaseControl
    {
        public Texture2D Picture;
        public Color ColorModifier;
        public event ControlEventHandler OnClick;

        private bool LeftWasPressed = false;

        public PictureButton(Texture2D picture) : base()
        {
            Picture = picture;
            Size = new Vector2(picture.Width, picture.Height);
            ColorModifier = Color.White;
        }

        public PictureButton(Texture2D picture, string name) : base() 
        {
            Picture = picture;
            Name = name;
            Size = new Vector2(picture.Width, picture.Height);
            ColorModifier = Color.White;
        }
        
        public override void Draw(GameTime gameTime, SpriteBatch spritebatch)
        {


            if (Visible)
            {

                spritebatch.Draw(Picture, new Rectangle(
                    (int)AbsoluteScreenPosition.X,
                    (int)AbsoluteScreenPosition.Y,
                    (int)Size.X,
                    (int)Size.Y), ColorModifier);

                base.Draw(gameTime, spritebatch);
            }
        }

        public override void Update(GameTime gameTime)
        {


            if (Visible)
            {

                MouseState mousestate = Mouse.GetState();
                Point mousepos = new Point(mousestate.X, mousestate.Y);
                Rectangle thisrect = new Rectangle((int)AbsoluteScreenPosition.X, (int)AbsoluteScreenPosition.Y, (int)Size.X, (int)Size.Y);

                if (thisrect.Contains(mousepos))
                {
                    if (mousestate.LeftButton == ButtonState.Pressed && LeftWasPressed == false)
                    {
                        if (gui.InputWasCaught == false)
                        {
                            LeftWasPressed = true;
                        }
                    }

                    if (LeftWasPressed)
                        gui.InputWasCaught = true;

                    if (mousestate.LeftButton == ButtonState.Released && LeftWasPressed == true)
                    {
                        if (OnClick != null)
                            OnClick(this);
                        LeftWasPressed = false;
                    }
                }
                else
                {
                    LeftWasPressed = false;
                }


                base.Update(gameTime);
            } // Visible?
        }
    }
}
